class Relationship < ActiveRecord::Base
    
    validates_uniqueness_of :name
    validates_presence_of   :name
    
    has_one :didily
        
    ##########################################################
    # Use to generate a tag cloud
    # This method expects that tags contain a 'id', 'name' and a 'count' value
    def self.cloud(tags, category_list)
        
        if tags and tags.length > 0
            max = 0
            min = tags[0].count.to_i
            tags.each do |tag|
                count = tag.count.to_i
                max = count if count > max
                min = count if count < min
            end
            
            divisor = ((max - min) / category_list.size) + 1
            
            tags.each do |tag|
                yield tag.id, tag.name, category_list[(tag.count.to_i - min) / divisor]             
            end
        end
    end
    
    ##########################################################
    # Finds today's most used relationships
    def self.todays_top(options = {})
        sql = "SELECT t.id, t.name, COUNT(t.id) AS count FROM tags t "
        sql << "INNER JOIN didilies_tags ON didilies_tags.tag_id = t.id "
        sql << "WHERE t.created_at > '" + days_ago(1) + "' GROUP BY t.id, t.name"
        sql << "ORDER BY t.name ASC "
        add_limit!(sql, options)
        
        connection.select_all(sql)
    end
    
    ##########################################################
    # Finds most used relationships
    def self.top(options = {})
        sql = "SELECT t.id, t.name, COUNT(t.id) AS count FROM tags t "
        sql << "INNER JOIN didilies_tags ON didilies_tags.tag_id = t.id "
        sql << "GROUP BY t.id, t.name"
        sql << "ORDER BY t.name ASC "
        add_limit!(sql, options)
        
        connection.select_all(sql)
    end
    
end